package com.han.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Properties;

/**
 * 类众安的签名加密与签名验签基础类
 * 
 * @author caopeng
 * 
 */
@Slf4j
public class AESUtil {
	@Autowired
	protected static Properties customerProperties;
	/**
	 * AES加密
	 */
	public static String encryptByAES(String content, String password) throws Exception {
	        try {
				if (content == null) {
					log.error("AES加密出错:Key为空null");
					return null;
				}
				// 判断Key是否为16位
				if (password.length() != 16) {
					log.error("AES加密出错:Key长度不是16位");
					return null;
				}
	            KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
	            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	            secureRandom.setSeed(password.getBytes("UTF-8"));
	            kgen.init(128,secureRandom);
	            SecretKey secretKey = kgen.generateKey();
	            byte[] enCodeFormat = secretKey.getEncoded();
	            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
	            // 创建密码器
	            Cipher cipher = Cipher.getInstance("AES");
	            byte[] byteContent = content.getBytes("UTF-8");
	            cipher.init(Cipher.ENCRYPT_MODE, key);
	            // 加密
	            byte[] result = cipher.doFinal(byteContent);
	            return (new sun.misc.BASE64Encoder()).encode(result);
	        } catch (Exception e) {

	           log.error("encryptByAES ASE加密出现异常",e);
	        }
	        return null;
	 }

	/**
	 * AES解密
	 */
	public static String decryptByAES(String contentStr, String password) throws Exception {
	        try {

				if (contentStr == null) {
					log.error("AES加密出错:Key为空null");
					return null;
				}
				// 判断Key是否为16位
				if (password.length() != 16) {
					log.error("AES加密出错:Key长度不是16位");
					return null;
				}
	            byte[] content = (new sun.misc.BASE64Decoder()).decodeBuffer(contentStr);
	            KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
	            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
	            secureRandom.setSeed(password.getBytes("UTF-8"));
	            kgen.init(128,secureRandom);
	            SecretKey secretKey = kgen.generateKey();

	            byte[] enCodeFormat = secretKey.getEncoded();
	            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
	            Cipher cipher = Cipher.getInstance("AES");
	            cipher.init(Cipher.DECRYPT_MODE, key);
	            byte[] result = cipher.doFinal(content);

	            return new String(result, "UTF-8");
	        } catch (Exception e) {

				log.error("decryptByAES ASE解密出现异常",e);
	        }
	        return null;
	}
}
